<template>
  <div class="comments-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>评价管理</h2>
      </div>
      <div class="header-right">
        <a-radio-group v-model="filterType" type="button">
          <a-radio value="all">全部评价</a-radio>
          <a-radio value="pending">待回复</a-radio>
          <a-radio value="replied">已回复</a-radio>
        </a-radio-group>
      </div>
    </div>

    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="false">
      <a-form :model="searchForm" layout="inline">
        <a-form-item field="keyword" label="搜索">
          <a-input
            v-model="searchForm.keyword"
            placeholder="商品名称/评价内容/用户名"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="rating" label="评分">
          <a-select
            v-model="searchForm.rating"
            placeholder="请选择评分"
            allow-clear
            style="width: 200px"
          >
            <a-option value="5">5星</a-option>
            <a-option value="4">4星</a-option>
            <a-option value="3">3星</a-option>
            <a-option value="2">2星</a-option>
            <a-option value="1">1星</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="dateRange" label="评价时间">
          <a-range-picker v-model="searchForm.dateRange" style="width: 260px" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 评价列表 -->
    <a-card class="list-card" :bordered="false">
      <a-table
        :data="commentList"
        :columns="columns"
        :pagination="pagination"
        @page-change="onPageChange"
        :sortable="true"
        @sorter-change="handleSorterChange"
      >
        <!-- 商品信息列 -->
        <template #productTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'product.name' &&
                    sortKeys.order === 'ascend',
                }"
                @click="handleSort('product.name', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'product.name' &&
                    sortKeys.order === 'descend',
                }"
                @click="handleSort('product.name', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 评价内容列 -->
        <template #contentTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'rating' && sortKeys.order === 'ascend',
                }"
                @click="handleSort('rating', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'rating' && sortKeys.order === 'descend',
                }"
                @click="handleSort('rating', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 评价时间列 -->
        <template #timeTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'createTime' &&
                    sortKeys.order === 'ascend',
                }"
                @click="handleSort('createTime', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'createTime' &&
                    sortKeys.order === 'descend',
                }"
                @click="handleSort('createTime', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 商品信息 -->
        <template #product="{ record }">
          <div class="product-info">
            <a-image
              :src="record.product.image"
              :width="60"
              :height="60"
              fit="cover"
            />
            <div class="product-detail">
              <div class="product-name">{{ record.product.name }}</div>
              <div class="product-price">¥{{ record.product.price }}</div>
            </div>
          </div>
        </template>

        <!-- 评价内容 -->
        <template #content="{ record }">
          <div class="comment-content">
            <div class="rating">
              <a-rate :model-value="record.rating" readonly />
              <span class="rating-text">{{ record.rating }}分</span>
            </div>
            <div class="content-text">{{ record.content }}</div>
            <div v-if="record.images?.length" class="content-images">
              <a-image-preview-group infinite>
                <a-image
                  v-for="(image, index) in record.images"
                  :key="index"
                  :src="image"
                  :width="80"
                  :height="80"
                  fit="cover"
                />
              </a-image-preview-group>
            </div>
            <div class="content-time">{{ record.createTime }}</div>
          </div>
        </template>

        <!-- 用户信息 -->
        <template #user="{ record }">
          <div class="user-info">
            <a-avatar :size="32" :src="record.user.avatar" />
            <span class="user-name">{{ record.user.name }}</span>
          </div>
        </template>

        <!-- 商家回复 -->
        <template #reply="{ record }">
          <div v-if="record.reply" class="reply-content">
            <div class="reply-text">{{ record.reply.content }}</div>
            <div class="reply-time">{{ record.reply.createTime }}</div>
          </div>
          <a-button v-else type="primary" @click="handleReply(record)">
            回复
          </a-button>
        </template>

        <!-- 操作 -->
        <template #operations="{ record }">
          <a-space>
            <a-button
              v-if="record.reply"
              type="text"
              @click="handleEditReply(record)"
            >
              编辑回复
            </a-button>
            <a-button type="text" status="danger" @click="handleReport(record)">
              举报
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 回复弹窗 -->
    <a-modal
      v-model:visible="replyVisible"
      :title="currentComment?.reply ? '编辑回复' : '回复评价'"
      @ok="handleReplySubmit"
      @cancel="handleReplyCancel"
    >
      <a-form :model="replyForm" layout="vertical">
        <a-form-item
          field="content"
          label="回复内容"
          :rules="[{ required: true, message: '请输入回复内容' }]"
        >
          <a-textarea
            v-model="replyForm.content"
            :min-rows="4"
            :max-rows="6"
            placeholder="请输入回复内容"
            show-word-limit
            :max-length="200"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconSearch,
  IconRefresh,
  IconUp,
  IconDown,
} from "@arco-design/web-vue/es/icon";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

// 原始评论列表数据
const originalCommentList = ref([
  {
    id: 1,
    product: {
      id: 1,
      name: "示例商品1",
      price: "99.00",
      image: "/images/products/product1.jpg",
    },
    rating: 5,
    content: "商品质量非常好，包装也很精美，很满意的一次购物体验！",
    images: [
      "/images/comments/comment1-1.jpg",
      "/images/comments/comment1-2.jpg",
    ],
    createTime: "2024-03-15 12:34:56",
    user: {
      id: 1,
      name: "张三",
      avatar: "/images/avatars/user1.jpg",
    },
    reply: {
      content: "感谢您的购买和好评，欢迎下次再来选购！",
      createTime: "2024-03-15 13:00:00",
    },
  },
  {
    id: 2,
    product: {
      id: 2,
      name: "示例商品2",
      price: "199.00",
      image: "/images/products/product2.jpg",
    },
    rating: 4,
    content: "商品不错，但是发货有点慢。",
    createTime: "2024-03-14 15:30:00",
    user: {
      id: 2,
      name: "李四",
      avatar: "/images/avatars/user2.jpg",
    },
  },
  {
    id: 3,
    product: {
      id: 3,
      name: "示例商品3",
      price: "299.00",
      image: "/images/products/product3.jpg",
    },
    rating: 3,
    content: "一般般吧，价格有点贵。",
    createTime: "2024-03-13 09:15:00",
    user: {
      id: 3,
      name: "王五",
      avatar: "/images/avatars/user3.jpg",
    },
    reply: {
      content: "非常抱歉没有让您满意，我们会继续改进。",
      createTime: "2024-03-13 10:00:00",
    },
  },
]);

// 展示用的评论列表
const commentList = ref([...originalCommentList.value]);

// 筛选类型
const filterType = ref("all");

// 更新评论列表函数
const updateCommentList = () => {
  // 根据筛选类型过滤评论列表
  const filteredList = originalCommentList.value.filter((comment) => {
    if (filterType.value === "pending") {
      return !comment.reply;
    }
    if (filterType.value === "replied") {
      return !!comment.reply;
    }
    return true; // 全部评价
  });

  // 更新表格数据
  commentList.value = filteredList;
};

// 监听路由参数变化
watch(
  () => route.query.type,
  (newType) => {
    filterType.value = newType || "all";
    // 根据筛选类型更新评论列表
    updateCommentList();
  },
  { immediate: true },
);

// 监听筛选类型变化
watch(filterType, (newValue) => {
  if (newValue === "all") {
    router.replace({ query: {} });
  } else {
    router.replace({ query: { type: newValue } });
  }
  // 根据筛选类型更新评论列表
  updateCommentList();
});

// 搜索表单
const searchForm = reactive({
  keyword: "",
  rating: null,
  dateRange: [],
});

// 排序状态
const sortKeys = reactive({
  field: "",
  order: "",
});

// 表格列配置
const columns = [
  {
    title: "商品信息",
    dataIndex: "product.name",
    slotName: "product",
    width: 240,
    sortable: { sortDirections: ["ascend", "descend"] },
    titleSlot: "productTitle",
  },
  {
    title: "评价内容",
    dataIndex: "rating",
    slotName: "content",
    sortable: { sortDirections: ["ascend", "descend"] },
    titleSlot: "contentTitle",
  },
  {
    title: "用户信息",
    dataIndex: "user",
    slotName: "user",
    width: 160,
  },
  {
    title: "商家回复",
    dataIndex: "reply",
    slotName: "reply",
    width: 200,
  },
  {
    title: "评价时间",
    dataIndex: "createTime",
    width: 160,
    sortable: { sortDirections: ["ascend", "descend"] },
    titleSlot: "timeTitle",
  },
  {
    title: "操作",
    slotName: "operations",
    width: 160,
    fixed: "right",
  },
];

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
});

// 回复弹窗
const replyVisible = ref(false);
const currentComment = ref(null);
const replyForm = reactive({
  content: "",
});

// 处理搜索
const handleSearch = () => {
  // TODO: 调用搜索API
  Message.success("搜索成功");
};

// 处理重置
const handleReset = () => {
  searchForm.keyword = "";
  searchForm.rating = null;
  searchForm.dateRange = [];
};

// 处理分页
const onPageChange = (page) => {
  pagination.current = page;
  // TODO: 加载对应页数据
};

// 处理回复
const handleReply = (record) => {
  currentComment.value = record;
  replyForm.content = "";
  replyVisible.value = true;
};

// 处理编辑回复
const handleEditReply = (record) => {
  currentComment.value = record;
  replyForm.content = record.reply.content;
  replyVisible.value = true;
};

// 处理回复提交
const handleReplySubmit = async () => {
  try {
    // TODO: 调用回复API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("回复成功");
    replyVisible.value = false;
  } catch (error) {
    Message.error("回复失败");
  }
};

// 处理回复取消
const handleReplyCancel = () => {
  currentComment.value = null;
  replyForm.content = "";
  replyVisible.value = false;
};

// 处理举报
const handleReport = (record) => {
  Message.success("举报成功");
};

// 处理表格排序变化
const handleSorterChange = (opt) => {
  if (!opt) {
    return;
  }

  const { field, direction } = opt;
  sortKeys.field = field;
  sortKeys.order = direction;
  handleSort(field, direction);
};

// 优化排序处理函数
const handleSort = (field, order) => {
  if (!field || !order) {
    return;
  }

  const sortedList = [...commentList.value];
  sortedList.sort((a, b) => {
    let compareA = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], a)
      : a[field];
    let compareB = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], b)
      : b[field];

    // 处理特殊字段
    if (field === "rating") {
      compareA = parseFloat(compareA) || 0;
      compareB = parseFloat(compareB) || 0;
    } else if (field === "createTime") {
      compareA = new Date(compareA).getTime();
      compareB = new Date(compareB).getTime();
    }

    if (order === "ascend") {
      return compareA > compareB ? 1 : -1;
    } else if (order === "descend") {
      return compareA < compareB ? 1 : -1;
    }
    return 0;
  });

  commentList.value = sortedList;
  Message.success(`${order === "ascend" ? "升序" : "降序"}排序成功`);
};
</script>

<style lang="scss" scoped>
.comments-page {
  .page-header {
    @apply flex items-center justify-between mb-6;

    h2 {
      @apply text-xl font-medium;
    }
  }

  .search-card {
    @apply mb-6;
  }

  .list-card {
    .product-info {
      @apply flex items-center space-x-4;

      .product-detail {
        @apply flex-1;

        .product-name {
          @apply text-sm font-medium mb-1;
        }

        .product-price {
          @apply text-sm text-red-500;
        }
      }
    }

    .comment-content {
      .rating {
        @apply flex items-center mb-2;

        .rating-text {
          @apply ml-2 text-sm text-gray-500;
        }
      }

      .content-text {
        @apply text-sm text-gray-700 mb-2;
      }

      .content-images {
        @apply flex flex-wrap gap-2 mb-2;
      }

      .content-time {
        @apply text-sm text-gray-500;
      }
    }

    .user-info {
      @apply flex items-center space-x-2;

      .user-name {
        @apply text-sm;
      }
    }

    .reply-content {
      .reply-text {
        @apply text-sm text-gray-600 mb-1;
      }

      .reply-time {
        @apply text-xs text-gray-400;
      }
    }
  }

  .column-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .sort-buttons {
      display: inline-flex;
      flex-direction: column;
      gap: 2px;
      margin-left: 4px;

      :deep(.arco-icon) {
        font-size: 12px;
        color: var(--color-text-3);
        cursor: pointer;
        line-height: 1;
        padding: 2px;

        &:hover,
        &.active {
          color: rgb(var(--primary-6));
        }
      }
    }
  }
}
</style>
